//
//  BYAdminHomeViewController.m
//  School+
//
//  Created by Sean Sebastian on 5/15/16.
//  Copyright © 2016 Sean Sebastian. All rights reserved.
//

#import "BYAdminHomeViewController.h"

#import "BYAdminHeaderView.h"
#import "masonry.h"

#import "UIImage+Extension.h"

#import "BYPhotoSelectorCell.h"
#import "BYLocationViewController.h"

#import "BYLocation.h"

#import "AFNetWorking.h"
#import "SVProgressHUD.h"
#import "AdminAccount.h"

#define reuseIdentifier @"Cell"
#define BYBoundary @"Sebastian-Sean"

@interface BYAdminHomeViewController () <UIImagePickerControllerDelegate , UINavigationControllerDelegate , UICollectionViewDataSource , UICollectionViewDelegate , BYPhotoSelectorCellDelegate ,BYAdminHeaderViewDelegate>

// header
@property (nonatomic , weak) BYAdminHeaderView *headerView;

// body
@property (nonatomic , weak) UIScrollView *scrollView;

@property (nonatomic , weak) UILabel *content_Label;
@property (nonatomic , weak) UITextView *content_TF;
@property (nonatomic , weak) UIButton *locationBtn;

@property (nonatomic , weak) UILabel *locationX_Label;
@property (nonatomic , weak) UILabel *locationY_Label;
@property (nonatomic , weak) UILabel *locationDetail_Label;

//@property (nonatomic , copy) NSString *locationImageURL;

@property (nonatomic , weak) UIView *lineView;

@property (nonatomic , weak) UILabel *addImageLabel;

// Photo Selector
@property (nonatomic , weak) UICollectionView *collectionView;
@property (nonatomic , strong) UICollectionViewFlowLayout *layout;

// 图片数组
@property (nonatomic , strong) NSMutableArray *photos;
// 记录点击的cell
@property (nonatomic , strong) NSIndexPath *currentIndexPath;
// 最大图片张数
@property (nonatomic , assign) int maxPhotoCount;

// footer
@property (nonatomic , weak) UIButton *submitBtn;


// 上传
@property (nonatomic , strong) NSMutableDictionary *imageDic;
@property (nonatomic , strong) NSMutableArray *imageNameArr;

// 拼接图片的字符串
@property (nonatomic , copy) NSMutableString *picURlString;

@end

@implementation BYAdminHomeViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self updateLocation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.collectionView registerClass:[BYPhotoSelectorCell class] forCellWithReuseIdentifier:reuseIdentifier];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *logout = [[UIBarButtonItem alloc] initWithTitle:@"logout" style:UIBarButtonItemStylePlain target:self action:@selector(logoutClick)];
    self.navigationItem.leftBarButtonItem = logout;
    


    [self prepareUI];
}


- (void)prepareUI
{
    [self.view addSubview:self.headerView];
    
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.content_Label];
    [self.scrollView addSubview:self.content_TF];
    [self.scrollView addSubview:self.locationBtn];
    [self.scrollView addSubview:self.locationX_Label];
    [self.scrollView addSubview:self.locationY_Label];
    [self.scrollView addSubview:self.locationDetail_Label];
    [self.scrollView addSubview:self.lineView];
    [self.scrollView addSubview:self.addImageLabel];
    [self.scrollView addSubview:self.collectionView];
    [self.view addSubview:self.submitBtn];
    
    CGFloat uiWidth = [UIScreen mainScreen].bounds.size.width - 30;
    
    self.content_Label.frame = CGRectMake(15, 10, uiWidth, 20);
    self.content_TF.frame = CGRectMake(15, CGRectGetMaxY(self.content_Label.frame) + 10 , uiWidth, 150);
    self.locationBtn.frame = CGRectMake(15, CGRectGetMaxY(self.content_TF.frame) + 10, uiWidth, 40);
    self.locationX_Label.frame = CGRectMake( 20 , CGRectGetMaxY(self.locationBtn.frame) + 5, 50, 15);
    self.locationY_Label.frame = CGRectMake(CGRectGetMaxX(self.locationX_Label.frame) + 10, CGRectGetMaxY(self.locationBtn.frame) + 5, 50, 15);
    self.locationDetail_Label.frame = CGRectMake(20, CGRectGetMaxY(self.locationY_Label.frame) + 5 , uiWidth, 15);
    self.lineView.frame = CGRectMake( 15, CGRectGetMaxY(self.locationDetail_Label.frame) + 5, uiWidth, 1);
    self.addImageLabel.frame = CGRectMake(20, CGRectGetMaxY(self.lineView.frame)+5, uiWidth, 20);
    self.collectionView.frame = CGRectMake(0, CGRectGetMaxY(self.addImageLabel.frame) + 5, [UIScreen mainScreen].bounds.size.width, 200);
}

- (void)updateLocation
{
    self.locationX_Label.text = [NSString stringWithFormat:@"X : %d" , [BYLocation sharedLocation].locationX];
    self.locationY_Label.text = [NSString stringWithFormat:@"Y : %d" , [BYLocation sharedLocation].locationY];
    if ([BYLocation sharedLocation].locationDetail == nil) {
        self.locationDetail_Label.text = @"Specific location :";
        [self.view setNeedsLayout];
        return;
    }
    self.locationDetail_Label.text = [NSString stringWithFormat:@"Specific location : %@" , [BYLocation sharedLocation].locationDetail];
    
//    self.locationImageURL = [BYLocation sharedLocation].locationImageURL;
    
//    NSLog(@"%@＝＝＝＝＝＝＝＝＝＝＝＝" , self.locationImageURL);
    
    [self.view setNeedsLayout];
}

// CollectionView Methods
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.photos.count < self.maxPhotoCount ? self.photos.count + 1 : self.photos.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    BYPhotoSelectorCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.cellDelegate = self;
    
    if (indexPath.item < self.photos.count) {
        cell.image = self.photos[indexPath.item];
    }else{
        [cell setAddButton];
    }
    return cell;
}


// cell Delegate methods
- (void)photoSelectorCellAddPhoto:(BYPhotoSelectorCell *)cell
{
    // 判断相册是否可用
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        NSLog(@"相册不可用");
        return;
    }
    
    // 弹出系统的相册
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.delegate = self;
    
    // 记录当前点击的cell的indexPath
    self.currentIndexPath = [self.collectionView indexPathForCell:cell];
    
    [self presentViewController:picker animated:YES completion:nil];
    
}

- (void)photoSelectorCellRemovePhoto:(BYPhotoSelectorCell *)cell
{
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    [self.photos removeObjectAtIndex:indexPath.item];
    
    [self.imageDic removeObjectForKey:self.imageNameArr[indexPath.item]];
    [self.imageNameArr removeObjectAtIndex:indexPath.item];
    
    
    
    if (self.photos.count < 3) {
        [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    }else{
        [self.collectionView reloadData];
    }
}

// photo selector
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary<NSString *,id> *)editingInfo
{
    // 把图片添加到image字典中便于上传
    // 用时间作为图片的名字
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMdd_HH-mm-ss"];
    NSString *dateStr = [formatter stringFromDate:date];
    
    [self.imageDic setValue:image forKey:dateStr];
    [self.imageNameArr addObject:dateStr];
    
    
    UIImage *newImage = [image scaleImage];
    
    if (self.currentIndexPath.item < self.photos.count) {
        // 点击图片
        self.photos[self.currentIndexPath.item] = newImage;
    }else{
        // 点击加号
        [self.photos addObject:image];
    }
    
    // 刷新数据
    [self.collectionView reloadData];
    
    
    // 关闭系统的相册
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)locationBtnClick
{
    
    UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:[[BYLocationViewController alloc] init]];
    
    [self presentViewController:nvc animated:YES completion:nil];
    [[BYLocation sharedLocation] clearLocation];
    
}

// submit Button Click
- (void)btnClick
{
    // 上传图片
    for (int i = 0 ; i < self.photos.count ; i++) {
        UIImage *image = self.photos[i];
        NSLog(@"%@" ,image);
        NSString *filename;
        NSData *data ;
        
        if(UIImageJPEGRepresentation(image, 1.0)){
            data = UIImageJPEGRepresentation(image, 1.0);
            filename =[NSString stringWithFormat:@"%@.jpg" , self.imageNameArr[i]];
        }else{
            data = UIImagePNGRepresentation(image);
            filename = [NSString stringWithFormat:@"%@.png" , self.imageNameArr[i]];

        }
        [self.picURlString appendFormat:@"%@***"  , filename];
        
        NSLog(@"%@" , self.picURlString);
        
        [self uploadFile:data fieldName:@"userfile" fileName:filename];
    }
    
    
    
    if ([BYLocation sharedLocation].locationImageData != nil) {
        UIImage *image = [UIImage imageWithData:[BYLocation sharedLocation].locationImageData];
        NSData *data = UIImagePNGRepresentation(image);
        NSString *filename = [NSString stringWithFormat:@"%d-%d-%@.jpg" ,[BYLocation sharedLocation].locationX , [BYLocation sharedLocation].locationY , [BYLocation sharedLocation].locationDetail];
        
//        [BYLocation sharedLocation].locationImageURL = filename;
        
//        NSLog(@"%@" ,  [BYLocation sharedLocation].locationImageURL );
        [self uploadLocationImage:data fieldName:@"userfile" fileName:filename];
        
    }
    
    
    
    NSURL *url = [NSURL URLWithString:@"http://localhost/SchoolPlus/insertBlog.php"];
    NSString *bodyStr = [NSString stringWithFormat:@"adminID=%d&content=%@&picURLs=%@&locationX=%d&locationY=%d&locationDetail=%@",[AdminAccount sharedAdminAccount].adminID,self.content_TF.text,self.picURlString , [BYLocation sharedLocation].locationX , [BYLocation sharedLocation].locationY , [BYLocation sharedLocation].locationDetail];
    // request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 设置请求方法
    request.HTTPMethod = @"POST";
    
    request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        
//        NSLog(@"%@--%@",response,result);
        
        
        [SVProgressHUD showInfoWithStatus:result[@"errorMessage"]];
        return ;
        
    }];
    
    [self performSelector:@selector(clearData) withObject:nil afterDelay:2.0];
    
}

- (void)clearData
{
    self.content_TF.text = @"";
    self.locationDetail_Label.text = @"Specific location : ";
    self.locationX_Label.text = @"X : 0";
    self.locationY_Label.text = @"Y : 0";
    [self.photos removeAllObjects];
    
    [self.collectionView reloadData];
    [self.view setNeedsLayout];
    
}

- (void)logoutClick
{
    NSLog(@"logoutClick！！！！");
}

// 上传
- (void)uploadFile:(NSData *)fileData fieldName:(NSString *)fieldName fileName:(NSString *)fileName{
    // url:负责文件上传的脚本
    NSURL *url = [NSURL URLWithString:@"http://localhost/SchoolPlus/upload.php"];
    
    // request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //    Content-Type	multipart/form-data; boundary=itcast
    // 设置content-type
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",BYBoundary] forHTTPHeaderField:@"Content-Type"];
    // 设置请求方法
    request.HTTPMethod = @"POST";
    // 设置请求体
    request.HTTPBody = [self fileData:fileData fieldName:fieldName fileName:fileName];
    
    // 发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"%@---%@",response,[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]);
    }];
}

- (void)uploadLocationImage:(NSData *)fileData fieldName:(NSString *)fieldName fileName:(NSString *)fileName{
    // url:负责文件上传的脚本
    NSURL *url = [NSURL URLWithString:@"http://localhost/SchoolPlus/uploadLocation.php"];
    
    // request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //    Content-Type	multipart/form-data; boundary=itcast
    // 设置content-type
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",BYBoundary] forHTTPHeaderField:@"Content-Type"];
    // 设置请求方法
    request.HTTPMethod = @"POST";
    // 设置请求体
    request.HTTPBody = [self fileData:fileData fieldName:fieldName fileName:fileName];
    
    // 发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"%@---%@",response,[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]);
    }];
}

- (NSData *)fileData:(NSData *)fileData fieldName:(NSString *)fieldName fileName:(NSString *)fileName{
    // 创建
    NSMutableData *dataM = [NSMutableData data];
    
    NSMutableString *strM = [NSMutableString stringWithFormat:@"--%@\r\n",BYBoundary];
    [strM appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",fieldName,fileName];
    [strM appendFormat:@"Content-Type:application/octet-stream\r\n\r\n"];
    
    // 设置头
    [dataM appendData:[strM  dataUsingEncoding:NSUTF8StringEncoding]];
    // 拼接文件数据
    [dataM appendData:fileData];
    
    // 拼接尾部
    NSString *tail = [NSString stringWithFormat:@"\r\n--%@--",BYBoundary];
    [dataM appendData:[tail dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    return dataM;
}



// lazy loading
- (BYAdminHeaderView *)headerView
{
    if (_headerView == nil) {
        BYAdminHeaderView *view = [[BYAdminHeaderView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width , 200)];
        view.delegate = self;
        _headerView = view;
        return view;
    }
    return _headerView;
}

- (void)logoutBtnClick
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"后台管理" message:@"确定退出？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.alertViewStyle = UIAlertViewStyleDefault;
    alert.delegate = self;
    [alert show];
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    // 取消按钮是第0个，确定键是第1个
    if (buttonIndex == 1) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    [alertView dismissWithClickedButtonIndex:0 animated:YES];
    
    
}

- (UIScrollView *)scrollView
{
    if (_scrollView == nil) {
        CGFloat scrollView_height = [UIScreen mainScreen].bounds.size.height - 200 - 50;
        UIScrollView *view = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 200, [UIScreen mainScreen].bounds.size.width, scrollView_height)];
        
        CGFloat color = 241.0/255.0;
        
        view.backgroundColor = [UIColor colorWithRed:color green:color blue:color alpha:1.0];
        
        _scrollView = view;
        return view;
    }
    return _scrollView;
}

- (UILabel *)content_Label
{
    if (_content_Label == nil) {
        UILabel *label = [[UILabel alloc] init];
        label.text = @"Contents";
        
        _content_Label = label;
        return label;
    }
    return _content_Label;
}

- (UITextView *)content_TF
{
    if (_content_TF == nil) {
        UITextView *tf = [[UITextView alloc] init];
        tf.backgroundColor = [UIColor whiteColor];
        tf.font = [UIFont systemFontOfSize:13];
        tf.showsVerticalScrollIndicator = YES;
        _content_TF = tf;
        return tf;
    }
    return _content_TF;
}

- (UIButton *)submitBtn
{
    if (_submitBtn == nil) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        btn.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 50, [UIScreen mainScreen].bounds.size.width, 50);
        [btn setTitle:@"Submit" forState:UIControlStateNormal];
        [btn setBackgroundColor:[UIColor orangeColor]];
        [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
        _submitBtn = btn;
        return btn;
    }
    return _submitBtn;
}

- (UIButton *)locationBtn
{
    if (_locationBtn == nil) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        [btn setTitle:@"insert a location" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setBackgroundColor:[UIColor blueColor]];
        [btn addTarget:self action:@selector(locationBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
        _locationBtn = btn;
        return btn;
    }
    return _locationBtn;
}

- (UILabel *)locationX_Label
{
    if (_locationX_Label == nil) {
        UILabel *label = [[UILabel alloc] init];
        label.text = @"X : 0";
        _locationX_Label = label;
        label.font = [UIFont systemFontOfSize:13];
        return label;
    }
    return _locationX_Label;
}

- (UILabel *)locationY_Label
{
    if (_locationY_Label == nil) {
        UILabel *label = [[UILabel alloc] init];
        label.text = @"Y : 0";
        label.font = [UIFont systemFontOfSize:13];
        _locationY_Label = label;
        return label;
    }
    return _locationY_Label;
}

- (UILabel *)locationDetail_Label
{
    if (_locationDetail_Label == nil) {
        UILabel *label = [[UILabel alloc] init];
        label.text = @"Specific location : ";
        label.numberOfLines = 0 ;
        label.font = [UIFont systemFontOfSize:14];
        _locationDetail_Label = label;
        return label;
    }
    return _locationDetail_Label;
}

- (UILabel *)addImageLabel
{
    if (_addImageLabel == nil) {
        UILabel *label = [[UILabel alloc] init];
        label.text = @"Add images (Maximum Value is four)";
        _addImageLabel = label;
        return label;
    }
    return _addImageLabel;
}

- (UIView *)lineView
{
    if (_lineView == nil) {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor blackColor];
        _lineView = view;
        return view;
    }
    return _lineView;
}

// Photo Selector
-(NSMutableArray *)photos
{
    if (_photos == nil) {
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        _photos = arr;
        return arr;
    }
    return _photos;
}

- (NSIndexPath *)currentIndexPath
{
    if (_currentIndexPath == nil) {
        NSIndexPath *indexPath = [[NSIndexPath alloc] init];
        _currentIndexPath = indexPath;
        return indexPath;
    }
    return _currentIndexPath;
}

- (int)maxPhotoCount
{
    return 4;
}

- (UICollectionViewFlowLayout *)layout
{
    if (_layout == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.itemSize = CGSizeMake(80, 80);
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        
        _layout = layout;
        return layout;
    }
    return _layout;
}

- (UICollectionView *)collectionView
{
    if (_collectionView == nil) {
        UICollectionView *view = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
        view.dataSource = self;
        view.delegate = self;
        
        _collectionView = view;
        return view;
    }
    return _collectionView;
}

- (NSMutableDictionary *)imageDic
{
    if (_imageDic == nil) {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        _imageDic = dict;
        return dict;
    }
    return _imageDic;
}

- (NSMutableArray *)imageNameArr
{
    if (_imageNameArr == nil) {
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        _imageNameArr = arr;
        return arr;
    }
    return _imageNameArr;
}

- (NSMutableString *)picURlString
{
    if (_picURlString == nil) {
        NSMutableString *str = [[NSMutableString alloc] init];
        _picURlString = str;
        return str;
    }
    return _picURlString;
}
@end
